package com.test.sort;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 并行模式奇偶排序使用
 * 
 * @author xuguangqiao
 *
 */
public class ParallelSort {

	static int exchFlag = 1;
	public static ReentrantLock lock = new ReentrantLock();
	public static int[] array;

	public static int getExchFlag() {
		return exchFlag;
	}

	public static void setExchFlag(int v) {
		lock.lock();
		try {
			exchFlag = v;
		} finally {
			lock.unlock();
		}
	}

	public static class OddEventSorkTask implements Runnable {

		int i;
		CountDownLatch latch;

		public OddEventSorkTask(int i, CountDownLatch latch) {
			this.i = i;
			this.latch = latch;
		}

		public void run() {
			if (array[i] > array[i + 1]) {
				int temp = array[i];
				array[i] = array[i + 1];
				array[i + 1] = temp;
				setExchFlag(1);
			}
			latch.countDown();
			//System.out.println("completed");
		}

	}

	public static void pOddEventSort(int[] arr) throws InterruptedException {
		ExecutorService pool = Executors.newFixedThreadPool(10);
		int start = 0;
		array = arr;
		while (getExchFlag() == 1 || start == 1) {
			setExchFlag(0);
			// 偶数的数组长度,当start为1时,只有len/2-1个线程
			CountDownLatch latch = new CountDownLatch(arr.length / 2 - (arr.length % 2 == 0 ? start : 1));
			for (int i = start; i < arr.length; i += 2) {
				pool.submit(new OddEventSorkTask(i, latch));
			}
			// 等待所有线程结束
			latch.await();
			if (start == 0) {
				start = 1;

			} else {
				start = 0;
			}
		}

	}

	public static void main(String[] args) throws InterruptedException {
		int len = 1000;
		int[] arr = new int[len];
		Random random = new Random();
		for (int i = 0; i < arr.length; i++) {
			arr[i] = random.nextInt(1000);
		}
		long start = System.currentTimeMillis();
		pOddEventSort(arr);
		// maoPoSort(arr);
		long end = System.currentTimeMillis();
		System.out.println(end - start);
	}

}
